<?php
namespace app\admin\controller;

use app\common\model\AdminIpsModel;
use app\common\model\AdminModel;
use app\common\model\MenuModel;
use app\common\model\RoleModel;

/**
 * 后台管理
 */
class Index extends Common
{
    /**
     * 首页
     * @author 贺强
     * @time   2018-10-25 14:13:15
     */
    public function index()
    {
        $admin = session('admin');
        if ($admin) {
            $m        = new MenuModel();
            $modular  = $this->get_menus($admin['role_id'], 1);
            $menu     = $this->get_menus($admin['role_id']);
            $where    = [];
            $list     = $m->getList($where, ['identity', 'title']);
            $list     = array_column($list, 'title', 'identity');
            $menu_str = json_encode($list);
            return view('index', compact('admin', 'modular', 'menu', 'menu_str'));
        }
        return $this->redirect('/login/index');
    }

    /**
     * 根据用户角色 ID 获取该用户的权限
     * @author 贺强
     * @time   2018-10-25 14:13:07
     * @param  integer $role_id 用户角色 ID
     * @return json    返回该用户拥有权限菜单
     */
    private function get_menus($role_id = 0, $modular = 0)
    {
        $where[] = [['is_delete', '=', 0], ['is_hide', '=', 0]];
        if ($role_id !== 1) {
            $r        = new RoleModel();
            $menus    = $r->getFieldValue('menus', ['id' => $role_id]);
            $menu_ids = explode(',', $menus);
            if (!empty($menu_ids)) {
                $where[] = ['id', 'in', $menu_ids];
            } else {
                $where[] = ['id', '=', 0];
            }
        }
        if ($modular) {
            $where[] = ['modular', '=', 0];
        } else {
            $where[] = ['modular', '>', 0];
        }
        $m    = new MenuModel();
        $list = $m->getList($where, true, null, ['pid', 'sort', 'id']);
        $arr  = [];
        foreach ($list as $item) {
            if ($item['pid'] === 0) {
                $arr[] = $item;
            } else {
                foreach ($arr as &$item2) {
                    if ($item['pid'] == $item2['id']) {
                        $item2['children'][] = $item;
                        break;
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 后台欢迎页
     * @author 贺强
     * @time   2018-10-25 14:12:59
     */
    public function index_v1()
    {
        return view('index_v2');
    }

    /**
     * 后台 IP 白名单
     * @author 贺强
     * @time   2020-02-21 12:29:55
     * @param  AdminIpsModel $ai AdminIpsModel 实例
     */
    public function ips(AdminIpsModel $ai)
    {
        // 判断是否有权限访问或操作
        $identity = strtolower($this->request->controller()) . '_' . strtolower($this->request->action());
        $admin    = $this->is_valid($identity);
        $where    = [];
        $keyword  = $this->request->post('keyword', '');
        if (!empty($keyword)) {
            $where[] = ['ip', 'like', "%{$keyword}%"];
        }
        // 分页参数
        $page     = intval($this->request->get('page', 1));
        $pagesize = intval($this->request->get('pagesize', config('app.PAGESIZE')));
        $list     = $ai->getList($where, true, [$page, $pagesize], ['login_time' => 'desc']);
        // print_r($list);exit;
        foreach ($list as &$item) {
            if (!empty($item['login_time'])) {
                format_datetime($item['login_time']);
            }
            if (!empty($item['ctime'])) {
                format_datetime($item['ctime']);
            }
        }
        $count = $ai->getCount($where);
        $pages = ceil($count / $pagesize);
        return view('ips', ['list' => $list, 'pages' => $pages, 'keyword' => $keyword]);
    }

    /**
     * 添加 IP 白名单
     * @author 贺强
     * @time   2020-02-21 12:41:50
     * @param  AdminIpsModel $i AdminIpsModel
     */
    public function addip(AdminIpsModel $i)
    {
        // 判断是否有权限访问或操作
        $identity = strtolower($this->request->controller()) . '_' . strtolower($this->request->action());
        $admin    = $this->is_valid($identity);
        if ($this->request->isAjax()) {
            $param = $this->request->post();
            if (empty($param['ip'])) {
                return ['status' => 1, 'info' => 'IP不能为空'];
            }
            $param['ip'] = trim($param['ip']);
            // 插入数据库
            $count = $i->getCount(['ip' => $param['ip']]);
            if ($count) {
                return ['status' => 2, 'info' => '此IP已加入白名单'];
            }
            if (!empty($param['username'])) {
                $i->delByWhere(['username' => $param['username']]);
            }
            $res = $i->add($param);
            if (!$res) {
                return ['status' => 4, 'info' => '添加失败'];
            }
            return ['status' => 0, 'info' => '添加成功'];
        }
        $a    = new AdminModel();
        $list = $a->getList(['is_delete' => 0], ['username']);
        return view('addip', compact('list'));
    }

    /**
     * 操作 IP 白名单
     * @author 贺强
     * @time   2020-02-21 12:38:38
     * @param  AdminIpsModel $i AdminIpsModel
     */
    public function delip(AdminIpsModel $i)
    {
        // 判断是否有权限访问或操作
        $identity = strtolower($this->request->controller()) . '_' . strtolower($this->request->action());
        $admin    = $this->is_valid($identity);
        if (!empty($admin['status'])) {
            return $admin;
        }
        if ($this->request->isAjax()) {
            $ids = $this->request->post('ids');
            if (empty($ids) || !preg_match('/^0[\,\d+]+$/', $ids)) {
                return ['status' => 3, 'info' => '非法参数'];
            }
            $type = $this->request->post('type');
            if (empty($type)) {
                return ['status' => 1, 'info' => '非法操作'];
            }
            $where = [['id', 'in', $ids]];
            if ($type === 'del' || $type === 'delAll') {
                $res = $i->delByWhere($where);
                $msg = '删除';
            } else {
                return ['status' => 2, 'info' => '非法操作'];
            }
            if ($res) {
                return ['status' => 0, 'info' => $msg . '成功'];
            } elseif ($res === false) {
                return ['status' => 4, 'info' => $msg . '失败'];
            } else {
                return ['status' => 5, 'info' => '该ip已' . $msg];
            }
        } else {
            return ['status' => 2, 'info' => '非法操作'];
        }
    }
}
